package com.htgd.gardenexpo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.WxUserCollectDao;
import com.htgd.gardenexpo.entity.GeConFood;
import com.htgd.gardenexpo.entity.GeConNews;
import com.htgd.gardenexpo.entity.GeConScene;
import com.htgd.gardenexpo.entity.WxUserCollect;
import com.htgd.gardenexpo.page.CollectQuery;
import com.htgd.gardenexpo.page.HealthyQuery;
import com.htgd.gardenexpo.page.SportQuery;
import com.htgd.gardenexpo.service.*;
import com.htgd.gardenexpo.utils.TokenUtil;
import com.htgd.gardenexpo.utils.UniteUtils;
import com.htgd.gardenexpo.vo.GeConHealthyVO;
import com.htgd.gardenexpo.vo.GeConSportVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户收藏表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-06-26
 */
@Service
public class WxUserCollectServiceImpl extends ServiceImpl<WxUserCollectDao, WxUserCollect> implements WxUserCollectService {

    @Autowired
    private GeConFoodService geConFoodService;

    @Autowired
    private WxUserCollectService wxUserCollectService;

    @Autowired
    private GeBaseDictService geBaseDictService;

    @Autowired
    private GeConNewsService geConNewsService;

    @Autowired
    private WxUserCollectDao wxUserCollectDao;

    @Autowired
    private GeConSceneService geConSceneService;

    @Autowired
    private GeConSportService geConSportService;

    @Autowired
    private GeConHealthyService geConHealthyService;

    @Override
    public Boolean isCollect(String openId, String typeId) {
        return lambdaQuery().eq(WxUserCollect::getUserId,openId)
                .eq(WxUserCollect::getTypeId,typeId).exists();
    }

    @Override
    public Boolean isLike(String openId,String typeId, String type) {
        return lambdaQuery().eq(WxUserCollect::getUserId,openId)
                .eq(WxUserCollect::getTypeId,typeId)
                .eq(WxUserCollect::getType,type).exists();
    }

    @Override
    public WxUserCollect selectOne(String openId, String typeId) {
        return lambdaQuery().eq(WxUserCollect::getUserId,openId)
                .eq(WxUserCollect::getTypeId,typeId).one();
    }

    @Override
    public Long getCollectAmount(String typeId, String type) {
        return lambdaQuery().eq(WxUserCollect::getTypeId,typeId)
                .eq(WxUserCollect::getType,type)
                .count();
    }

    @Override
    public WxUserCollect getIdByOpenIdAndTypeId(String openId, String typeId) {
        WxUserCollect wxUserCollect = lambdaQuery().eq(WxUserCollect::getTypeId,typeId)
                .eq(WxUserCollect::getUserId,openId)
                .select(WxUserCollect::getId,WxUserCollect::getType,WxUserCollect::getTypeId)
                .one();
        return wxUserCollect;
    }

    @Override
    public long getFoodCollectAmount(Integer id) {
        return  lambdaQuery().eq(WxUserCollect::getTypeId,id)
                .eq(WxUserCollect::getType,"food")
                .count();
    }

    /**
     * 按照分类获取我的收藏列表
     * @return
     */
    @Override
    public List<HashMap> getMyCollectList(CollectQuery collectQuery, HttpServletRequest request) {
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        //美食
        if(Objects.equals(collectQuery.getType(),"food")){
            List<WxUserCollect> list = wxUserCollectDao.getFoodCollectByOpenIdAndType(openId,"food");
//            List<WxUserCollect> list = wxUserCollectDao.selectList(new LambdaQueryWrapper<WxUserCollect>()
//                .eq(WxUserCollect::getType,"food")
//                .eq(WxUserCollect::getUserId,openId)
//                .orderByDesc(WxUserCollect::getId));
            List<Integer> foodIds = list.stream().map(x->Integer.valueOf(x.getTypeId())).collect(Collectors.toList());
            if(!foodIds.isEmpty()){
                Page<GeConFood> page = new Page<>(collectQuery.getPageNum(), collectQuery.getPageSize());
                IPage<GeConFood> foodList = geConFoodService.page(page,new LambdaQueryWrapper<GeConFood>()
                        .in(GeConFood::getId,foodIds));
                foodList.getRecords().stream().forEach(item->{
                    //收藏
                    item.setCollect(false);
                    if(openId!=null){
                        Boolean collect = wxUserCollectService.isCollect(openId, String.valueOf(item.getId()));
                        item.setCollect(collect);
                    }
                    //点赞数
                    Long collectAmount = wxUserCollectService.getCollectAmount(String.valueOf(item.getId()), "food");
                    item.setCollectAmount(collectAmount);
                    //标签
                    if(item.getType()!=null){
                        String typeText = "";
                        String[] split = item.getType().split(",");
                        for (String s : split) {
                            String food_type = geBaseDictService.getTextByCodeAndValue("food_type", s);
                            typeText = typeText + food_type + ",";
                        }
                        item.setTypeText(typeText.substring(0,typeText.length()-1));
                    }
                });
                List<HashMap> result = foodList.getRecords().stream()
                    .map(obj -> {
                        HashMap<String, Object> map = new HashMap<>();
                        Class<?> clazz = obj.getClass();
                        for (Field field : clazz.getDeclaredFields()) {
                            field.setAccessible(true); // 使得私有属性也可以访问
                            try {
                                map.put(field.getName(), field.get(obj));
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                        // 将其他属性添加到Map中
                        return map;
                    })
                    .collect(Collectors.toList());
                return result;
            }
        }
        //新闻资讯
        if(Objects.equals(collectQuery.getType(),"news")){
            List<WxUserCollect> list = wxUserCollectDao.getNewsCollectByOpenIdAndType(openId,"news");
            List<Integer> newsIds = list.stream().map(x->Integer.valueOf(x.getTypeId())).collect(Collectors.toList());
            if(!newsIds.isEmpty()){
                List<GeConNews> newsList = geConNewsService.queryAllByLimit1(newsIds,collectQuery.getPageNum()-1, collectQuery.getPageSize());
                newsList.stream().forEach(item->{
                    Boolean collect = wxUserCollectService.isLike(openId, item.getNewId().toString(),"news");
                    if (collect) {
                        item.setIsLike(true);
                    }else{
                        item.setIsLike(false);
                    }
                    String content= UniteUtils.stripHtml(item.getNewContent().toString());
                    if (!content.equals("")){
                        item.setNewContent(content.substring(0,content.length()>200?200:content.length()));
                    }else {
                        item.setNewContent("");
                    }
                });
                List<HashMap> result = newsList.stream()
                    .map(obj -> {
                        HashMap<String, Object> map = new HashMap<>();
                        Class<?> clazz = obj.getClass();
                        for (Field field : clazz.getDeclaredFields()) {
                            field.setAccessible(true); // 使得私有属性也可以访问
                            try {
                                map.put(field.getName(), field.get(obj));
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                        // 将其他属性添加到Map中
                        return map;
                    })
                    .collect(Collectors.toList());
                return result;
            }
        }
        //景观地标
        if(Objects.equals(collectQuery.getType(),"scene")){
            List<WxUserCollect> list = wxUserCollectDao.getSceneCollectByOpenIdAndType(openId,"scene");
            Page<GeConScene> page = new Page<>(collectQuery.getPageNum(), collectQuery.getPageSize());
            List<Integer> sceneIds = list.stream().map(x->Integer.valueOf(x.getTypeId())).collect(Collectors.toList());
            if(!sceneIds.isEmpty()){
                IPage<GeConScene> sceneList = geConSceneService.page(page,
                        new LambdaQueryWrapper<GeConScene>()
                                .in(GeConScene::getId,sceneIds));
                sceneList.getRecords().stream().forEach(item->{
                    Boolean collect = wxUserCollectService.isLike(openId, item.getId().toString(),"scene");
                    if (collect) {
                        item.setIsLike(true);
                    }else{
                        item.setIsLike(false);
                    }
                });
                List<HashMap> result = sceneList.getRecords().stream()
                        .map(obj -> {
                            HashMap<String, Object> map = new HashMap<>();
                            Class<?> clazz = obj.getClass();
                            for (Field field : clazz.getDeclaredFields()) {
                                field.setAccessible(true); // 使得私有属性也可以访问
                                try {
                                    map.put(field.getName(), field.get(obj));
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }
                            // 将其他属性添加到Map中
                            return map;
                        })
                        .collect(Collectors.toList());
                return result;
            }
        }
        //运动科普
        if(Objects.equals(collectQuery.getType(),"sport")){
            List<WxUserCollect> list = wxUserCollectDao.getSportCollectByOpenIdAndType(openId,"sport");
            List<String> sportIds = list.stream().map(x->x.getTypeId()).collect(Collectors.toList());
            if(!sportIds.isEmpty()){
                SportQuery sportQuery = new SportQuery();
                sportQuery.setPageNum(collectQuery.getPageNum());
                sportQuery.setPageSize(collectQuery.getPageSize());
                sportQuery.setIds(sportIds);
                PageInfo<GeConSportVO> sportList = geConSportService.pageList(sportQuery,request);
                List<HashMap> result = sportList.getList().stream()
                    .map(obj -> {
                        HashMap<String, Object> map = new HashMap<>();
                        Class<?> clazz = obj.getClass();
                        for (Field field : clazz.getDeclaredFields()) {
                            field.setAccessible(true); // 使得私有属性也可以访问
                            try {
                                map.put(field.getName(), field.get(obj));
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                        // 将其他属性添加到Map中
                        return map;
                    })
                    .collect(Collectors.toList());
                return result;
            }
        }
        //健康科普
        if(Objects.equals(collectQuery.getType(),"healthy")){
            List<WxUserCollect> list = wxUserCollectDao.getHealthyCollectByOpenIdAndType(openId,"healthy");
            List<Integer> healthyIds = list.stream().map(x->Integer.valueOf(x.getTypeId())).collect(Collectors.toList());
            if(!healthyIds.isEmpty()){
                HealthyQuery healthyQuery = new HealthyQuery();
                healthyQuery.setPageNum(collectQuery.getPageNum());
                healthyQuery.setPageSize(collectQuery.getPageSize());
                healthyQuery.setIds(healthyIds);
                PageInfo<GeConHealthyVO> healthyList = geConHealthyService.pageList(healthyQuery,request);
                List<HashMap> result = healthyList.getList().stream()
                    .map(obj -> {
                        HashMap<String, Object> map = new HashMap<>();
                        Class<?> clazz = obj.getClass();
                        for (Field field : clazz.getDeclaredFields()) {
                            field.setAccessible(true); // 使得私有属性也可以访问
                            try {
                                map.put(field.getName(), field.get(obj));
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                        // 将其他属性添加到Map中
                        return map;
                    })
                    .collect(Collectors.toList());
                return result;
            }
        }
        return new ArrayList<>();
    }

    @Override
    public Long getMyCollectListCount(CollectQuery collectQuery, HttpServletRequest request) {
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        if(Objects.equals(collectQuery.getType(),"food")){
            Long count = lambdaQuery().eq(WxUserCollect::getType,"food")
                    .eq(WxUserCollect::getUserId,openId)
                    .count();
            return count;
        }
        if(Objects.equals(collectQuery.getType(),"news")) {
            Long count = lambdaQuery().eq(WxUserCollect::getType,"news")
                    .eq(WxUserCollect::getUserId,openId)
                    .count();
            return count;
        }

        //景观地标
        if(Objects.equals(collectQuery.getType(),"scene")){
            Long count = lambdaQuery().eq(WxUserCollect::getType,"scene")
                    .eq(WxUserCollect::getUserId,openId)
                    .count();
            return count;
        }
        //运动科普
        if(Objects.equals(collectQuery.getType(),"sport")){
            Long count = lambdaQuery().eq(WxUserCollect::getType,"sport")
                    .eq(WxUserCollect::getUserId,openId)
                    .count();
            return count;
        }
        //健康科普
        if(Objects.equals(collectQuery.getType(),"healthy")){
            Long count = lambdaQuery().eq(WxUserCollect::getType,"healthy")
                    .eq(WxUserCollect::getUserId,openId)
                    .count();
            return count;
        }
        return 0L;
    }
}
